package com.aptemo.webetek.server.services;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aptemo.webetek.client.exceptions.BackendException;
import com.aptemo.webetek.server.data.PMF;
import com.aptemo.webetek.server.datastore.DataStoreHelper;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * The server side implementation of the Invitation service.
 */
public class RecalcUserService
		extends HttpServlet
{

	/**
	 * 
	 */
	private static final long	serialVersionUID	= 2442498766498504653L;

	/**
	 * 
	 */
	private UserService			userService			= UserServiceFactory.getUserService();

	private DataStoreHelper		dataHelper			= new DataStoreHelper();

	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
	{
		res.setContentType("text/html");

		String url = req.getRequestURI().toString();
		String queryString = req.getQueryString();
		if (queryString != null)
		{
			url += "?" + queryString;
		}

		String id = req.getParameter("id");

		String loginUrl = userService.createLoginURL(url);
		if (!userService.isUserLoggedIn() && !userService.isUserAdmin())
		{
			res.sendRedirect(loginUrl);
			return;
		}

		// 
		String redirect = null;
		try
		{
			redirect = recalculation(id);

			res.sendRedirect(redirect);
		}
		catch (BackendException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// TODO....
		res.sendRedirect("error");
	}

	private String recalculation(String id) throws BackendException
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
			// get user
			Key key = KeyFactory.stringToKey(id);
			// WebetekUser user = pm.getObjectById(WebetekUser.class, key);

			// recalc bets...
			dataHelper.recalcUserCounters(id);

			return "/#standings-" + KeyFactory.keyToString(key.getParent());
		}
		finally
		{
			pm.close();
		}

	}
}
